<script lang="ts" setup>

import {onMounted, reactive, ref, type UnwrapRef} from "vue";
import {message} from "ant-design-vue";
import {useRouter} from "vue-router";
import {useInfoStore} from "@/store/user/user.ts";
import {pageInterviewAPI, updateInterviewStatusAPI} from "@/apis/interview.ts";
import type {Dayjs} from "dayjs";
import type {Rule} from "ant-design-vue/es/form";
import {addOfferAPI} from "@/apis/offer.ts";
import {addNewAPI} from "@/apis/new.ts";

//表单数据
interface FormState {
  resumeUsername: string
  jobTitle: string
  offerJobseekerId: string
  offerJobId: string
  offerEmployerId: string
  offerStatus: string
  offerEndTime: Dayjs | null | string
  offerRemarks: string
}

const formState: UnwrapRef<FormState> = reactive({
  resumeUsername: '',
  jobTitle: '',
  offerJobseekerId: '',
  offerJobId: '',
  offerEmployerId: '',
  offerStatus: '',
  offerEndTime: null,
  offerRemarks: '',

});

//拒绝消息
interface RefuseNewState {
  newCreatorId: string
  newReceiverId: string
  newCreatorName: string | null
  newCreatorAvatar: string | null
  newReceiverName: string
  newTitle: string
  newText: string
  resumeUsername: string
  jobTitle: string
}

const formRef2 = ref();
const refuseNewState: UnwrapRef<RefuseNewState> = reactive({
  newCreatorId: '',
  newReceiverId: '',
  newCreatorName: '',
  newCreatorAvatar: '',
  newReceiverName: '',
  newTitle: '',
  newText: '',
  resumeUsername: '',
  jobTitle: '',
});
const rules2: Record<string, Rule[]> = {
  newText: [
    {required: true, message: '请输入拒绝原因', trigger: 'change'},
  ],
  resumeUsername: [
    {required: true, message: '请选择截止时间', trigger: 'change'},
  ],
  jobTitle: [
    {required: true, message: '请选择截止时间', trigger: 'change'},
  ],
};

const rules1: Record<string, Rule[]> = {
  offerEndTime: [
    {required: true, message: '请选择截止时间', trigger: 'change'},
  ],
  resumeUsername: [
    {required: true, message: '请选择截止时间', trigger: 'change'},
  ],
  jobTitle: [
    {required: true, message: '请选择截止时间', trigger: 'change'},
  ],
  offerRemarks: [
    {required: true, message: '请补充备注信息', trigger: 'change'},
  ],
};

const formRef = ref();
const onSubmit1 = (item: any) => {
  formRef.value
      .validate()
      .then(async () => {
        //添加Offer
        addOfferAPI({
          offerJobseekerId: item.interviewJobseekerId,
          offerJobId: item.interviewJobId,
          offerEmployerId: item.interviewEmployerId,
          offerStatus: "待接受",
          offerRemarks: formState.offerRemarks,
          offerEndTime: formState.offerEndTime,
        }).then((res) => {
          if (res.data.flag) {
            updateInterviewStatusAPI({
              interviewId: item.interviewId,
              interviewStatus: "已处理",
            }).then((res) => {
              if (res.data.flag) {
                message.success('发出Offer成功')
                // 设置一个定时器，1秒（1000毫秒）后执行页面刷新
                setTimeout(function () {
                  list.splice(0, list.length);
                  getList(pageDate.value);
                }, 1500);
              } else {
                message.error('发出Offer失败')
              }
            })
          } else {
            message.error('添加失败')
          }
          open1.value = false;
        })
      })
      .catch((error: any) => {
        console.log('error', error);
      });
};
const onSubmit2 = (item: any) => {
  formRef2.value
      .validate()
      .then(async () => {
        refuseNewState.newCreatorId = userStore.userId;
        refuseNewState.newReceiverId = item.interviewJobseekerId;
        refuseNewState.newCreatorName = userStore.userName;
        refuseNewState.newCreatorAvatar = userStore.userAvatarUrl;
        refuseNewState.newReceiverName = item.resumeUsername;
        refuseNewState.newTitle = '您投递的--' + item.jobTitle + '--职位被拒绝录用了';
        //添加消息
        const res = await addNewAPI(refuseNewState);
        if (res.data.flag) {
          message.success('拒绝录用成功');
          //修改投递状态
          updateInterviewStatusAPI({interviewId: item.interviewId, interviewStatus: "已处理"}).then((res) => {
            if (res.data.flag) {
              open2.value = false;
              setTimeout(() => {
                list.splice(0, list.length);
                getList(pageDate.value);
              }, 1500);
            }
          })
        }
      })
      .catch((error: any) => {
        console.log('error', error);
      });
}
//分页查询岗位和企业信息
const count = 8;
const pageCurrent = ref(1);
const pageTotal = ref(0);
const initLoading = ref(true);
const loading = ref(false);
const list = <any>reactive([]);
//用户信息
const userStore = useInfoStore().userInfo;
const pageDate = <any>ref({
  interviewStatus: '已完成',
  interviewEmployerId: '',
  pageCurrent: pageCurrent.value,
  pageSize: count,
});

const getList = async (pageDate: any) => {
  pageDate.interviewEmployerId = userStore.userId;
  const res = await pageInterviewAPI(pageDate);
  if (res.data.flag) {
    pageTotal.value = res.data.data.total;
    list.push(...res.data.data.data)
    initLoading.value = false;
  } else {
    message.error(res.data.message)
  }
}

//生命周期
onMounted(() => {
  getList(pageDate.value);
});

const onLoadMore = () => {
  loading.value = true;
  initLoading.value = true;
  pageCurrent.value += 1;
  getList(pageDate.value).then(() => {
    loading.value = false;
  });
};

//查看
const router = useRouter();
const goToInterviewDetail = (interviewId: string) => {
  router.push({
    name: 'interviewDetail',
    params: {
      interviewId: interviewId // 确保传递的参数为字符串类型
    }
  });
};

//通过-发出Offer
const open1 = ref<boolean>(false);
const showModal1 = (item: any) => {
  open1.value = true;
  interviewDate.interviewJobseekerId = item.interviewJobseekerId
  interviewDate.interviewId = item.interviewId
  interviewDate.interviewEmployerId = item.interviewEmployerId
  interviewDate.interviewJobId = item.interviewJobId
  formState.resumeUsername = item.resumeUsername
  formState.jobTitle = item.jobTitle
};
const handleOk1 = (item: any) => {
  onSubmit1(item)
};
//拒绝-录用
const open2 = ref<boolean>(false);
const showModal2 = (item: any) => {
  open2.value = true;
  interviewDate.resumeUsername = item.resumeUsername
  refuseNewState.resumeUsername = item.resumeUsername
  interviewDate.interviewJobseekerId = item.interviewJobseekerId
  interviewDate.interviewJobId = item.interviewJobId
  interviewDate.interviewId = item.interviewId
  interviewDate.interviewEmployerId = item.interviewEmployerId
  interviewDate.jobTitle = item.jobTitle
  refuseNewState.jobTitle = item.jobTitle
};
const handleOk2 = (item: any) => {
  onSubmit2(item)
};
const interviewDate = reactive({
  interviewJobseekerId: '',
  resumeUsername: '',
  jobTitle: '',
  interviewId: '',
  interviewEmployerId: '',
  interviewJobId: '',
})


</script>
<template>
  <a-modal v-model:open="open1" :title="'发出-'+formState.resumeUsername+'的Offer！'" cancelText="取消"
           okText="确认" @ok="handleOk1(interviewDate)"
  >
    <a-form
        ref="formRef"
        :model="formState"
        :rules="rules1"
    >
      <div style="
              border: 1px solid #4D7181;
              border-radius: 20px;
              display: flex;
              align-items: center;
              justify-items: center;
              flex-direction: column;">
        <a-divider orientation="center" style="color:#4D7181; font-size: 20px">Offer-信息</a-divider>
        <a-form-item ref="resumeUsername" label="Offer-姓名" name="resumeUsername">
          <a-input v-model:value="formState.resumeUsername" :disabled="true"
                   style="width: 350px;"/>
        </a-form-item>
        <a-form-item ref="jobTitle" label="Offer-岗位" name="jobTitle">
          <a-input v-model:value="formState.jobTitle" :disabled="true"
                   style="width: 350px;"/>
        </a-form-item>
        <a-form-item ref="offerEndTime" label="截止-时间" name="offerEndTime">
          <a-date-picker v-model:value="formState.offerEndTime"
                         show-time
                         style="width: 350px;"/>
        </a-form-item>
        <a-form-item ref="offerRemarks" label="补充-信息"
                     name="offerRemarks">
          <a-textarea v-model:value="formState.offerRemarks"
                      :auto-size="{minRows: 4, maxRows: 10}"
                      :maxlength="300"
                      show-count
                      style="width: 350px"
          />
        </a-form-item>
      </div>
    </a-form>
  </a-modal>

  <a-modal v-model:open="open2" :title="'拒绝-录用'+interviewDate.resumeUsername+'！'" cancelText="取消"
           okText="确认" @ok="handleOk2(interviewDate)">
    <a-form
        ref="formRef2"
        :model="refuseNewState"
        :rules="rules2"
    >
      <div style="
              border: 1px solid #4D7181;
              border-radius: 20px;
              display: flex;
              align-items: center;
              justify-items: center;
              flex-direction: column;">
        <a-divider orientation="center" style="color:#4D7181; font-size: 20px">拒绝-信息</a-divider>
        <a-form-item ref="resumeUsername" label="求职-姓名" name="resumeUsername">
          <a-input v-model:value="refuseNewState.resumeUsername" :disabled="true"
                   style="width: 350px;"/>
        </a-form-item>
        <a-form-item ref="jobTitle" label="求职-岗位" name="jobTitle">
          <a-input v-model:value="refuseNewState.jobTitle" :disabled="true"
                   style="width: 350px;"/>
        </a-form-item>
        <a-form-item ref="newText" label="拒绝-原因"
                     name="newText">
          <a-textarea v-model:value="refuseNewState.newText"
                      :auto-size="{minRows: 4, maxRows: 10}"
                      :maxlength="300"
                      show-count
                      style="width: 350px"
          />
        </a-form-item>
      </div>
    </a-form>
  </a-modal>
  <div class="add_job">
    <div class="top">
      <a-page-header
          sub-title="添加Offer表单"
          title="返回"
          @back="() => $router.go(-1)"
      />
      <a-divider orientation="left" style="color:#4D7181; font-size: 20px;padding: 0 50px">面试-列表</a-divider>
    </div>
    <div class="bottom">
      <div class="main-content">
        <a-list
            :data-source="list"
            :loading="initLoading"
            class="demo-loadmore-list"
            item-layout="horizontal"
        >
          <template #loadMore>
            <div
                v-if="!initLoading && !loading && list.length < pageTotal"
                :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }"
            >
              <a-button @click="onLoadMore">获取更多</a-button>
            </div>
          </template>
          <template #renderItem="{ item }">

            <a-list-item>
              <template #actions>
                <a-button type="primary" @click="goToInterviewDetail(item.interviewId)">查看信息</a-button>
                <a-button style="color: white;background-color: #67C23A" @click="showModal1(item)">发出Offer</a-button>
                <a-button style="color: white;background-color: red" @click="showModal2(item)">拒绝录用</a-button>


              </template>
              <a-skeleton :loading="!!item.loading" :title="false" active avatar>
                <a-list-item-meta
                    :description="item.interviewType+'&nbsp;&nbsp;&nbsp;&nbsp'+item.jobLocation"
                >
                  <template #title>
                    {{ item.resumeUsername }}&nbsp;&nbsp;&nbsp;&nbsp;{{ item.jobTitle }}&nbsp;&nbsp;&nbsp;&nbsp;状态 :
                    {{ item.interviewStatus }}
                  </template>
                  <template #avatar>
                    <a-avatar
                        :size="54"
                        :src="'http://localhost:8080/image/download?name=' + item.resumeAvatar"
                    />
                  </template>
                </a-list-item-meta>
                <a-badge-ribbon :text="item.resumeEducationSchool" color="blue">
                  <div style="border-radius: 10px;width: 180px;background-color: #EAF2FF;padding: 10px">
                    <div>
                      学历: {{ item.resumeEducationDegree }}
                    </div>
                    <div>
                      性别: {{ item.resumeGender }} &nbsp&nbsp&nbsp&nbsp 年龄: {{ item.resumeAge }}
                    </div>
                  </div>
                </a-badge-ribbon>
              </a-skeleton>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </div>

  </div>

</template>

<style scoped>
.add_job {
  width: 100%;
  height: 100%;

  .bottom {
    padding-right: 50px;


  }

}
</style>
